<template>
  <!-- FBA发货单 -->
  <div class="delivery-list-wrap table-gl-w">
    <a-tabs @change="changeStatus" size="mini">
      <a-tab-pane key="" title="全部" />
      <a-tab-pane v-for="tab in Object.values(tabsMap)" :key="tab.key">
        <template #title>
          <span>{{ tab.title }}</span>
          <span v-if="tab.key">({{ countMap[tab.key] || 0 }})</span>
        </template>
      </a-tab-pane>
    </a-tabs>

    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" :showExport="true" :exportInfo="exportInfo" :seachData="seachData" :checkedList="selectIds" @refresh="getTableList">
        <template #headerLeft>
          <a-space>
            <a-button type="primary" size="medium" v-if="(!searchVal.status || searchVal.status === 'DRAFT') && $authPass('procurement.fba.shipment.sale.save')" @click="openEditFba({})">创建发货单</a-button>
            <a-button class="gray-outline" v-if="searchVal.status === 'DRAFT' && $authPass('procurement.fba.shipment.sale.submit')" size="medium" @click="submitAudit(selectIds)">提交处理</a-button>
            <a-button class="gray-outline" v-if="searchVal.status === 'INBOX' && $authPass('procurement.fba.shipment.sale.revokeDraft')" size="medium" @click="submitRevocationWait(selectIds)">撤回待处理</a-button>
            <a-button class="gray-outline" v-if="searchVal.status === 'TO_BE_BIND' && $authPass('procurement.fba.shipment.sale.revokeInbox')" size="medium" @click="submitRevocationBox(selectIds)">撤回装箱中</a-button>
            <a-button class="gray-outline" v-if="searchVal.status === 'TO_BE_BIND' && $authPass('procurement.fba.shipment.sale.transShip')" size="medium" @click="toShipmentBatch(selectIds)">转待发货</a-button>
            <a-button class="gray-outline" v-if="['TO_BE_SHIPPED', 'SHIPPED', 'FINISHED', 'ERROR'].includes(searchVal.status)" size="medium" @click="syncFba(selectIds)">同步FBA货件</a-button>
            <a-button class="gray-outline" v-if="searchVal.status === 'TO_BE_SHIPPED' && $authPass('procurement.fba.shipment.sale.shipment')" size="medium" @click="openFbaShipment">确认发货</a-button>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-two-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :data="tableList"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :bordered="{ headerCell: true }"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left" key="sort">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="shopName" title="店铺" :width="100" fixed="left" key="shopName">
                <template #cell="{ record }">
                  <TextLimit>{{ record.shopName }}</TextLimit>
                </template>
              </a-table-column>
              <a-table-column data-index="billNo" title="发货单号" :width="130" fixed="left" key="billNo">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight cursor" @click="toDetail(record)">{{ record.billNo }}</p>
                    <span v-if="record.urgent" class="urgent">急</span>
                    <CopyText class="popup-edit-icon-hover" :val="record.billNo" />
                  </a-space>
                  <p v-if="record.printPackingList" class="warningColor">已打印</p>
                </template>
              </a-table-column>
              <a-table-column data-index="status" title="发货单状态" v-if="searchVal.status != 'DRAFT'" :width="90" fixed="left" key="status">
                <template #cell="{ record }">
                  <p>{{ $extract(tabsMap[record.status], 'title') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="logisticsMethod" title="物流方式" :width="70" fixed="left" key="logisticsMethod" />
              <a-table-column data-index="warehouseName" title="发货仓" :width="100" fixed="left" key="warehouseName" />
              <a-table-column data-index="shipFromAddress" title="发货地址" :width="100" key="shipFromAddress">
                <template #cell="{ record }">
                  <TextLimit>{{ getAddress(record.shipFromAddress) }}</TextLimit>
                </template>
              </a-table-column>
              <template v-if="searchVal.status != 'DRAFT'">
                <a-table-column title="收货仓" :width="100" key="centerId">
                  <template #cell="{ record }">
                    <p>{{ record.centerId }}</p>
                  </template>
                </a-table-column>
                <a-table-column data-index="shipToAddress" title="收货地址" :width="100" key="shipToAddress">
                  <template #cell="{ record }">
                    <TextLimit>{{ getAddress(record.shipToAddress) }}</TextLimit>
                  </template>
                </a-table-column>
                <a-table-column data-index="shipmentId" title="FBA货件号" :width="140" key="shipmentId">
                  <template #cell="{ record }">
                    <div class="flex-c-sb">
                      <p v-if="!record.shipmentId" style="color: #999">未绑定货件</p>
                      <p v-else>{{ record.shipmentId }}</p>
                      <template v-if="record.status == 'TO_BE_BIND' && $authPass('procurement.fba.shipment.sale.bind')">
                        <icon-edit v-if="record.shipmentId" @click="openBindDialog(record)" class="edit-icon cursor" />
                        <icon-link v-else @click="openBindDialog(record)" class="edit-icon cursor" />
                      </template>
                    </div>
                  </template>
                </a-table-column>
                <a-table-column data-index="centerId" title="CenterId" :width="80" key="centerId1" />
                <a-table-column data-index="amzStatus" title="FBA货件状态" :width="90" key="amzStatus" />
                <a-table-column title="数量" key="num">
                  <a-table-column data-index="realNum" title="发货数" :width="60" key="realNum">
                    <template #cell="{ record }">
                      <a-popover title="发货单明细" trigger="click" position="bottom">
                        <p class="highlight cursor">{{ record.realNum }}<icon-down style="margin-left: 5px" /></p>
                        <template #content>
                          <FbaItems :list="record.skuDetails" :status="record.status" />
                        </template>
                      </a-popover>
                    </template>
                  </a-table-column>
                  <a-table-column data-index="receiveNum" title="入库数" :width="60" key="receiveNum" />
                  <a-table-column data-index="stayAmt" title="差异" :width="60" key="stayAmt">
                    <template #cell="{ record }">
                      <p>{{ Number(record.realNum || 0) - Number(record.receiveNum || 0) }}</p>
                    </template>
                  </a-table-column>
                </a-table-column>
                <a-table-column title="费用" key="fee">
                  <a-table-column title="运费" :width="60" key="shipFee">
                    <template #cell="{ record }">
                      <p>￥{{ record.shipFee }}</p>
                    </template>
                  </a-table-column>
                  <a-table-column title="处理费" :width="60" key="laborCost">
                    <template #cell="{ record }">
                      <p>￥{{ record.laborCost }}</p>
                    </template>
                  </a-table-column>
                </a-table-column>
                <a-table-column title="货值" :width="80" key="productValue">
                  <template #cell="{ record }">
                    <p>￥{{ record.productValue }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="入库货值" :width="80" key="receiveValue">
                  <template #cell="{ record }">
                    <p>￥{{ record.receiveValue }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="箱数" :width="70" key="boxNum">
                  <template #cell="{ record }">
                    <a-popover trigger="click" v-if="record.boxDetails" position="bottom">
                      <p class="highlight cursor">{{ record.boxDetails.length }}<icon-down style="margin-left: 5px" /></p>
                      <template #content>
                        <BoxItems :list="record.boxDetails" :detail="record" @print="printBox(record)" />
                      </template>
                    </a-popover>
                    <p v-else>--</p>
                  </template>
                </a-table-column>
                <a-table-column title="物流渠道" :width="100" key="logisticChannel">
                  <template #cell="{ record }">
                    <p>{{ $extract(record.logisticsInfo, 'logisticChannelName') }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="承运商/跟踪号" :width="100" key="carrier">
                  <template #cell="{ record }">
                    <p class="warningColor" v-if="record.logisticErrorMsg">{{ record.logisticErrorMsg }}</p>
                    <template v-else>
                      <p>{{ $extract(record.logisticsInfo, 'logisticName') }}</p>
                      <TextLimit :rows="1">{{ $extract(record.logisticsInfo, 'logisticsTrackNumber') }}</TextLimit>
                    </template>
                  </template>
                </a-table-column>
              </template>
              <template v-else>
                <a-table-column data-index="realNum" title="发货数" :width="100" key="realNum1">
                  <template #cell="{ record }">
                    <div class="flex-c">
                      <a-popover title="发货单明细" trigger="click" position="bottom">
                        <p class="highlight cursor">{{ record.realNum }}<icon-down style="margin-left: 5px" /></p>
                        <template #content>
                          <FbaItems :list="record.skuDetails" :status="record.status" />
                        </template>
                      </a-popover>
                      <span v-if="record.marks && record.marks.includes('缺货')" style="margin-left: 10px" class="warningColor">缺货</span>
                    </div>
                  </template>
                </a-table-column>
                <a-table-column title="货值" :width="80" key="productValue">
                  <template #cell="{ record }">
                    <p>￥{{ record.productValue }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="是否可合并" :width="80" key="merged">
                  <template #cell="{ record }">
                    <p v-if="record.merged" class="highlight cursor" @click="openMergeDialog(record)">可合并</p>
                    <p v-else>否</p>
                  </template>
                </a-table-column>
              </template>
              <a-table-column data-index="createUname" title="创建人" :width="70" key="createUname" />
              <a-table-column title="创建时间" :width="130" key="gmtCreate">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate, 'YYYY/MM/DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <template v-if="searchVal.status != 'DRAFT'">
                <a-table-column title="提交处理时间" :width="130" key="gmtSubmit">
                  <template #cell="{ record }">
                    <p>{{ $setTime(record.gmtSubmit, 'YYYY/MM/DD HH:mm') }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="发货时间" :width="130" key="gmtShipped">
                  <template #cell="{ record }">
                    <p>{{ $setTime(record.gmtShipped, 'YYYY/MM/DD HH:mm') }}</p>
                  </template>
                </a-table-column>
                <a-table-column title="入库时间(市场时间)" :width="130" key="gmtReceive">
                  <template #cell="{ record }">
                    <p>{{ $setTime(record.gmtReceive, 'YYYY/MM/DD HH:mm') }}</p>
                  </template>
                </a-table-column>
              </template>

              <a-table-column title="操作" :width="100" fixed="right" key="handle">
                <template #cell="{ record }">
                  <a-space>
                    <a-button type="text" v-if="record.status == 'DRAFT' && $authPass('procurement.fba.shipment.sale.edit')" @click="openEditFba(record)">编辑</a-button>
                    <a-button type="text" v-else-if="record.status == 'TO_BE_BIND' && $authPass('procurement.fba.shipment.sale.bind')" @click="openBindDialog(record)">绑定货件</a-button>
                    <a-button type="text" v-else @click="toDetail(record)">详情</a-button>
                    <a-dropdown>
                      <icon-more class="table-btn-more" />
                      <template #content>
                        <a-doption @click.stop="submitAudit([record.id])" v-if="record.status == 'DRAFT' && $authPass('procurement.fba.shipment.sale.submit')">提交处理</a-doption>
                        <a-doption @click.stop="submitDelete([record.id])" v-if="record.status == 'DRAFT' && $authPass('procurement.fba.shipment.sale.delete')">删除</a-doption>
                        <a-doption @click.stop="submitRevocationWait([record.id], record)" v-if="record.status == 'INBOX' && $authPass('procurement.fba.shipment.sale.revokeDraft')">撤回待处理</a-doption>
                        <a-doption @click.stop="submitRevocationBox([record.id], record)" v-if="record.status == 'TO_BE_BIND' && $authPass('procurement.fba.shipment.sale.revokeInbox')">撤回装箱中</a-doption>
                        <a-doption v-if="record.status == 'TO_BE_BIND' && record.shipmentId && $authPass('procurement.fba.shipment.sale.transShip')" @click="toShipmentBatch([record.id], record)">转待发货</a-doption>
                        <a-doption v-if="record.status == 'TO_BE_SHIPPED' && $authPass('procurement.fba.shipment.sale.shipment')">确认发货</a-doption>
                        <a-doption v-if="record.status == 'SHIPPED'" @click="printBox(record)">打印装箱单</a-doption>
                        <a-doption v-if="record.status == 'SHIPPED'" @click="openLogisticsManifest(record)">打印物流面单</a-doption>
                        <a-doption v-if="['TO_BE_SHIPPED', 'SHIPPED', 'FINISHED', 'ERROR'].includes(record.status)" @click="syncFba([record.id], record)">同步货件</a-doption>
                        <a-doption v-if="record.status == 'TO_BE_BIND'" @click="toDetail(record)">详情</a-doption>
                        <a-doption @click.stop="openLogList(record)">日志</a-doption>
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 转待发货校验提示-->
  <a-modal :width="500" v-model:visible="showToShipmentError" title="转到待发货状态" title-align="start" :mask-closable="false">
    <p>以下发货单，未绑定FBA货件，无法转到待发货。</p>
    <ul>
      <template v-for="(item, i) in selectRows" :key="i">
        <li class="warningColor" style="margin-bottom: 5px" v-if="!item.shipmentId">{{ item.billNo }}</li>
      </template>
    </ul>
  </a-modal>
  <!-- 合并FBA货件 -->
  <MergeFba v-if="showMergeDialog" :isShow="showMergeDialog" :currentData="currentData" @closed="showMergeDialog = false" @success="getListAndCount" />
  <!-- 绑定FBA货件 -->
  <BindFbaCode v-if="showBindDialog" source="sale" :isShow="showBindDialog" :currentData="currentData" @closed="showBindDialog = false" @success="getListAndCount" />
  <!-- 添加&编辑FBA货件 -->
  <AddAndEditFba v-if="showEditFbaDialog" :isShow="showEditFbaDialog" :currentData="currentData" @closed="showEditFbaDialog = false" @success="getListAndCount" />
  <!-- 日志列表 -->
  <CommonLogsDialog v-if="showLogDialog" api="findFbaShipmentLogPage" :id="currentData.id" :isShow="showLogDialog" @closed="showLogDialog = false" />
  <!-- 确认发货 -->
  <FbaShipment v-if="showFbaShipment" source="sale" :isShow="showFbaShipment" :list="currentData" @closed="showFbaShipment = false" @success="getListAndCount" />
  <!-- 打印装箱单 -->
  <PrintFbaBox v-if="showPrintBox" :isShow="showPrintBox" :currentData="currentData" @closed="showPrintBox = false" />
</template>
<script lang="ts">
  export default defineComponent({
    name: 'DeliveryList',
  })
</script>
<script lang="ts" setup>
  import { ref, onMounted, reactive, defineComponent } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem, ExportInfo } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { useRouter } from 'vue-router'
  import CommonLogsDialog from '@/components/Log/logsDialog.vue'
  import BindFbaCode from './components/bindFbaCode.vue'
  import FbaItems from './components/fbaItems.vue'
  import AddAndEditFba from './components/addAndEditFba.vue'
  import BoxItems from './components/boxItems.vue'
  import MergeFba from './components/mergeFba.vue'
  import { findFbaShipmentPageBySale, syncFbaShipmentAmazon, findFbaShipmentCountBySaleStatus, findFbaShipmentAddressList, submitFbaShipmentBySale, transFbaShipmentToShipBySale, revokeFbaShipmentToInboxBySale, deleteFbaShipmentBySale, revokeFbaShipmentToDraftBySale } from '@/api/purchase'
  import useBaseDataStore from '@/store/modules/base-data'
  import PrintFbaBox from '@/views/warehouse/fbaDelivery/components/printFbaBox.vue'
  import FbaShipment from '@/views/warehouse/fbaDelivery/components/fbaShipment.vue'
  import { fbaItemExportSheet, fbaExportSheet, fbaBoxExportSheet } from '@/utils/exportFiled'
  onMounted(() => {
    getWareHouseList()
    getListAndCount()
    getUserList()
    getShopList()
    getFbaWareHouseList()
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'shopId',
      label: '店铺',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      type: 'input_keyword',
      key: 'billNos',
      keyItems: [
        { label: '发货单号', value: 'billNos' },
        { label: '货件号', value: 'shipmentIds' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 160,
      isMultiple: true,
    },
    {
      type: 'input_keyword',
      key: 'skus',
      keyItems: [
        { label: 'SKU', value: 'skus' },
        { label: 'MSKU', value: 'mskus' },
        { label: 'FNSKU', value: 'fnskus' },
        { label: 'ASIN', value: 'asins' },
      ],
      keyWidth: '90',
      value: ref(),
      placeholder: '请输入',
      label: '',
      width: 150,
      isMultiple: true,
    },
    {
      key: 'centerId',
      label: '目的仓库',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'warehouseCode',
      label: '发货仓',
      value: ref(),
      type: 'select',
      width: 120,
      optionItems: [],
    },
    {
      key: 'createUid',
      label: '创建人',
      value: ref(),
      type: 'select',
      width: 90,
      optionItems: [],
    },
    {
      key: 'shipmentType',
      label: '类型',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [
        { label: '海外仓发货计划', value: '2' },
        { label: 'FBA仓发货计划', value: '1' },
      ],
    },
    {
      key: 'logisticsMethod',
      label: '物流方式',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        { label: '空运', value: '空运' },
        { label: '海运', value: '海运' },
      ],
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [
        { label: '创建日期', value: 'gmtCreate' },
        { label: '发货日期', value: 'gmtShipped' },
        { label: '入库日期', value: 'gmtFinished' },
      ],
      keyWidth: '100',
      value: ref(),
      placeholder: '请输入',
      label: '创建时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const exportInfo: ExportInfo = {
    title: '导出发货单',
    type: 'batch',
    supportAll: true,
    exportDatas: [
      {
        tabName: '导出明细信息',
        fieldList: fbaItemExportSheet,
        supportTemplate: true,
        templateType: 'FBA_ITEM_EXPORT_TEMPLATE_SALE',
        exportApi: 'exportFbaShipmentDetailBySale',
        excelName: 'fbaItem',
      },
      {
        tabName: '导出发货单信息',
        fieldList: fbaExportSheet,
        supportTemplate: true,
        templateType: 'FBA_EXPORT_TEMPLATE_SALE',
        exportApi: 'exportFbaShipmentBySale',
        excelName: 'fba',
      },
      {
        tabName: '导出装箱信息',
        fieldList: fbaBoxExportSheet,
        supportTemplate: true,
        templateType: 'FBA_BOX_EXPORT_TEMPLATE_SALE',
        exportApi: 'exportFbaShipmentBoxInfoBySale',
        excelName: 'fbaBox',
      },
    ],
  }
  const tabsMap = {
    DRAFT: { key: 'DRAFT', title: '待处理' },
    INBOX: { key: 'INBOX', title: '装箱中' },
    TO_BE_BIND: { key: 'TO_BE_BIND', title: '绑定货件' },
    TO_BE_SHIPPED: { key: 'TO_BE_SHIPPED', title: '待发货' },
    SHIPPED: { key: 'SHIPPED', title: '已发货' },
    FINISHED: { key: 'FINISHED', title: '已入库' },
    ERROR: { key: 'ERROR', title: '取消/异常' },
  }
  const countMap = ref<any>({})
  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    status: '',
  })
  const total = ref(0)
  const tableLoading = ref(false)
  const showBindDialog = ref(false)
  const showEditFbaDialog = ref(false)
  const showMergeDialog = ref(false)
  const tableList = ref<Array<any>>([])
  const selectIds = ref([])
  const selectRows = ref<any>([])
  const tableRef = ref()
  const showToShipmentError = ref(false)
  const router = useRouter()
  const filterData = ref<any>({})
  const tableListMap = ref({})
  const showLogDialog = ref(false)
  const currentData = ref<any>({})
  const useBaseData = useBaseDataStore()
  const showFbaShipment = ref(false)
  const showPrintBox = ref(false)
  const seachData = ref<any>({})

  // 打开确认发货
  function openFbaShipment(list?: any) {
    if (list?.length) {
      currentData.value = list
    } else {
      getSelectRows()
      currentData.value = selectRows.value
    }
    if (!currentData.value.length) {
      Message.error('请选择发货单')
      return
    }
    showFbaShipment.value = true
  }
  // 详情
  function toDetail(item: any) {
    router.push(`/purchase/fbaManagement/deliveryDetail?id=${item.id}`)
  }
  // 打印物流面单
  function openLogisticsManifest(row: any) {
    let url = row?.logisticsInfo?.logisticsManifest
    if (!url) {
      Message.error('未上传物流面单')
      return
    }
    window.open(url, '_block')
  }
  // 打印箱单
  function printBox(item: any) {
    currentData.value = item
    showPrintBox.value = true
  }
  // 获取FBA收货仓地址列表
  async function getFbaWareHouseList() {
    const res: any = await findFbaShipmentAddressList()
    let list = res?.data || []
    let optionItems = list.map((el: any) => {
      return {
        label: el.centerId,
        value: el.centerId,
      }
    })
    filterItem.value[3].optionItems = optionItems
  }
  // 获取仓库列表
  async function getWareHouseList() {
    await useBaseData.getWareHouseList()
    let optionItems = useBaseData.warehouseList.map((el: any) => {
      return {
        label: el.warehouseName,
        value: el.warehouseCode,
      }
    })
    filterItem.value[4].optionItems = optionItems
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    filterItem.value[0].optionItems = useBaseData.shopList.map((el: any) => {
      return {
        label: el.shopName,
        value: el.sellerMarketId,
      }
    })
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    filterItem.value[5].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.status = status
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 查询列表和数量合计
  function getListAndCount() {
    getTableList()
    getCountList()
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 查询各状态下数量合计
  async function getCountList() {
    const res: any = await findFbaShipmentCountBySaleStatus()
    let counts = res?.data || []
    countMap.value = {}
    counts.forEach((el: any) => {
      countMap.value[el.status] = el.totalCount
    })
  }
  // 获取商品列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData.value,
    }
    tableLoading.value = true
    const res: any = await findFbaShipmentPageBySale(params)
    seachData.value = params
    tableRef.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    tableListMap.value = {}
    tableList.value.forEach((el: any) => {
      tableListMap.value[el.id] = el
    })
  }
  // 显示地址
  function getAddress(address: any) {
    return `${address?.countryCode || ''}${address?.stateOrProvinceCode || ''}${address?.city || ''}${address?.addressLine1 || ''}`
  }
  // 撤回待处理
  function submitRevocationWait(ids: Array<string>, row?: any) {
    if (!ids.length) {
      Message.error('请选择发货单')
      return
    }
    getSelectRows()
    let billNos = row ? [row.billNo] : selectRows.value.map((el: any) => el.billNo)
    Modal.confirm({
      title: '撤回待处理',
      content: `请再次确认是否需要将发货单:${billNos.join(',')} 撤回待处理！一旦撤回将会解锁库存！`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await revokeFbaShipmentToDraftBySale({ ids: ids })
        if (res) {
          Message.success('撤回成功')
          getListAndCount()
        }
      },
    })
  }
  // 撤回装箱中
  function submitRevocationBox(ids: Array<string>, row?: any) {
    if (!ids.length) {
      Message.error('请选择发货单')
      return
    }
    getSelectRows()
    let billNos = row ? [row.billNo] : selectRows.value.map((el: any) => el.billNo)
    Modal.confirm({
      title: '撤回',
      content: `请再次确认是否需要将发货单:${billNos.join(',')} 撤回重新装箱！`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await revokeFbaShipmentToInboxBySale({ ids: ids })
        if (res) {
          Message.success('撤回成功')
          getListAndCount()
        }
      },
    })
  }
  // 转待发货
  function toShipmentBatch(ids: Array<string>, row?: any) {
    if (!ids.length) {
      Message.error('请选择发货单')
      return
    }
    getSelectRows()
    showToShipmentError.value = selectRows.value.some((el: any) => !el.shipmentId)
    if (showToShipmentError.value) return
    let billNos = row ? [row.billNo] : selectRows.value.map((el: any) => el.billNo)
    Modal.confirm({
      title: '转待发货',
      content: `请再次确认是否将发货单:${billNos.join(',')} 转入待发货！`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await transFbaShipmentToShipBySale({ ids: ids })
        if (res) {
          Message.success('撤回成功')
          getListAndCount()
        }
      },
    })
  }
  // 同步FBA货件
  function syncFba(ids: Array<string>, row?: any) {
    if (!ids.length) {
      Message.error('请选择发货单')
      return
    }
    getSelectRows()
    let billNos = row ? [row.billNo] : selectRows.value.map((el: any) => el.billNo)
    Modal.confirm({
      title: '同步',
      content: `请再次确认是否需要同步货件:${billNos.join(',')}`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await syncFbaShipmentAmazon({ ids: ids })
        if (res) {
          Message.success('同步成功')
          getListAndCount()
        }
      },
    })
  }

  // 删除
  function submitDelete(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择发货单')
      return
    }
    Modal.confirm({
      title: '删除',
      content: `请再次确认是否需要删除选中的发货单`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await deleteFbaShipmentBySale({ ids: ids })
        if (res) {
          Message.success('删除成功')
          getListAndCount()
        }
      },
    })
  }
  function getSelectRows() {
    selectRows.value = []
    selectIds.value.map((id) => {
      selectRows.value.push(tableListMap.value[id])
    })
  }
  // 打开日志列表
  function openLogList(row: any) {
    currentData.value = row
    showLogDialog.value = true
  }
  // 提交处理
  function submitAudit(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择发货单')
      return
    }
    Modal.confirm({
      title: '提交处理',
      content: `请再次确认是否将选中发货单提交处理`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await submitFbaShipmentBySale({ ids: ids })
        if (res) {
          Message.success('提交处理成功')
          getListAndCount()
        }
      },
    })
  }
  // 打开绑定FBA货件
  function openBindDialog(row: any) {
    currentData.value = row
    showBindDialog.value = true
  }
  // 打开编辑FBA货件
  function openEditFba(row: any) {
    currentData.value = row
    showEditFbaDialog.value = true
  }
  // 打开合并货件
  function openMergeDialog(row: any) {
    currentData.value = row
    showMergeDialog.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
  .urgent {
    font-size: 12px;
    background-color: red;
    color: #fff;
    width: 18px;
    border-radius: 50%;
    line-height: 18px;
    text-align: center;
    transform: scale(0.82);
  }
  .edit-icon {
    flex-shrink: 0;
    margin-left: 5px;
    display: none;
    font-size: 16px;
  }
  :deep(.arco-table-tr) {
    &:hover .edit-icon {
      display: inline-block;
    }
  }
</style>
